﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WebApp.Services;

namespace WebApp.Controllers
{
    [Produces("application/json")]
    [Route("api/Dapper")]
    public class DapperController : Controller
    {
        private readonly DapperService _dapperService;
        public DapperController(DapperService dapperService)
        {
            _dapperService = dapperService;
        }


        // GET api/values/id
        [HttpGet("{id}")]
        public string Get(int id)
        {

            using (var conn = _dapperService.GetConnection())
            {
                var m = conn.Query<TestModel>("select * from TestModel where id=?id", new { id = id }).FirstOrDefault();
                return JsonConvert.SerializeObject(m);
            }


            //// 分页
            //var l = _sqlLiteContextService.TestModels.Where(c=>c.Id>2 && c.Id<5).OrderByDescending(c => c.Id)
            //    .Skip(1).Take(2);
            //return JsonConvert.SerializeObject(l.ToList());
        }


        // POST api/values
        [HttpPost]
        public string Post([FromBody]string key)
        {
            using (var conn = _dapperService.GetConnection())
            {
                var m = new TestModel
                {
                    Name = key
                };
                var strSql = new StringBuilder(1000);
                strSql.Append("insert into TestModel(");
                strSql.Append("id,name)");
                strSql.Append(" values (");
                strSql.Append("?Id,?Name);");
                strSql.Append("SELECT LAST_INSERT_ID();");

                var rel = conn.ExecuteScalar(strSql.ToString(), m);
                conn.Close();

                return rel.ToString();


            }

        }



    }
}